
import {constEtEnum} from "./enum"
import {NewFile, OpenFile, OpenOnLineFile} from "./etProcessFunction"
import {setToken, setTenantId, removeToken, getAccessToken, getRefreshToken} from '@/utils/auth'
import {deleteUserCache, setUserCache} from "@/hooks/web/useCache";
import {useUserStoreWithOut} from "@/store/modules/user";
import {
  fileInfoEnum,
  GetDocParamsValue,
  sendWebNotify,
  setDocParamsValue
} from "@/components/WpsOffice/common/common";
import {
  pCheckIs996CodeOffice,
  saveEtToServer,
  savePdfoServer
} from "@/components/WpsOffice/et/etCommon";

/**
 * web页面调用WPS的方法入口
 *  * info参数结构
 * info:[
 *      {
 *       '方法名':'方法参数',需要执行的方法
 *     },
 *     ...
 *   ]
 * @param {*} info
 */
let testFuncs=null;
function  dispatcher(info) {
    try {
      var funcs = info.funcs;
      // 清理用户信息
      if(getRefreshToken() != info.REFRESH_TOKEN){
          removeToken()
          deleteUserCache()
      }
      // 设置token
      {
          const tokenObj = {}
          tokenObj.accessToken = info.ACCESS_TOKEN
          tokenObj.refreshToken = info.REFRESH_TOKEN
          tokenObj.userCache = JSON.parse(info.USER_CACHE)
          setToken(tokenObj)
          setTenantId(info.tenantId);
          setUserCache(tokenObj.userCache)
          // const userStore = useUserStoreWithOut()
          // userStore.setUserInfoAction()
      }

      //解析参数
      /**
       * 分两种情况解析：
       * 1、业务系统依赖客户端返回：做同步处理，直接在for循环中返回
       */
      for (var index = 0; index < funcs.length; index++) {
          var func = funcs[index];
          for (var key in func) {
            func[key][fileInfoEnum.routeId] = info[fileInfoEnum.routeId]
            func[key][fileInfoEnum.officeId] = info[fileInfoEnum.officeId]
            if (key === "ExitET") {
              ExitET(func[key])
            } else if (key === "SaveET") {
              SaveET(func[key])
            } else if (key === "SavePDF") {
              SavePDF(func[key])
            }
          }
      }
      /**
       * 2、业务系统不依赖客户端返回：
       * 做异步处理，先返回接收状态，再在setTimeout中做打开文档的一系列业务逻辑
       */
      setTimeout(function(){
        try {
          for (var index = 0; index < funcs.length; index++) {
              testFuncs=funcs;
              var func = funcs[index];
              for (var key in func) {
                  // 标记文档类型
                  func[key][constEtEnum.is996Code]=true;
                  func[key][fileInfoEnum.routeId] = info[fileInfoEnum.routeId]
                  func[key][fileInfoEnum.officeId] = info[fileInfoEnum.officeId]
                  if (key === "NewEt") {
                      OpenEt(func[key]);
                  }
                  if (key === "OpenEt") {
                      OpenEt(func[key]);
                  }
                  if (key === "OnlineEditEt") {
                      OnlineEditEt(func[key]);
                  }
                  if (key === "PrintTemplateEt") {
                    PrintTemplateEt(func[key])
                  }
              }
          }
        }catch (e) {
          alert("WPS命令执行失败："+e.message)
          alert(e.stack)
        }
      },100)
    }catch (e) {
        alert("OnAddinLoad执行失败："+e.message)
        alert(e.stack)
    }
    return {message:"ok", app:wps.EtApplication().Name}
}


///打开来自OA端传递来的文档
function OpenEt(docParams) {
  if (docParams.filePathUrl == null || docParams.filePathUrl == "") {
    NewFile(docParams);
  }else {
    OpenFile(docParams);
  }
}

function   OnlineEditEt(docParams) {
  if (docParams.filePathUrl == null || docParams.filePathUrl == "") {
    NewFile(docParams);
  } else {
    //OA传来下载文件的URL地址，调用openFile 方法打开
    OpenOnLineFile(docParams);
  }
}

/**
 * 关闭WPS活动文档并退出WPS进程
 */
function ExitET(param) {

  let count = wps.EtApplication().Workbooks.Count;
  let paramActiveEtId = param[constEtEnum.ActiveEtId];
  for(let i=1;i<=count;i++) {
    let l_doc = wps.EtApplication().Workbooks.Item(i)
    // 判断是否是需要保存的文件
    let activeEtId = GetDocParamsValue(l_doc,constEtEnum.ActiveEtId);
    if(paramActiveEtId.includes(activeEtId)){
      l_doc.Close();
    }
  }
}

async function SaveET(param) {
  let saveEtToServerRes = {};
  //为了接下来的用户确认操作，先将WPS界面激活显示在最前
  // wps.WpsApplication().Activate();
  let count = wps.EtApplication().Workbooks.Count;
  let paramActiveEtId = param[constEtEnum.ActiveEtId];
  let callEtTraceId = param[constEtEnum.CallEtTraceId];
  for(let i=1;i<=count;i++) {
    let l_doc = wps.EtApplication().Workbooks.Item(i)
    // 判断是否是需要保存的文件
    let activeEtId = GetDocParamsValue(l_doc,constEtEnum.ActiveEtId);
    if(paramActiveEtId.includes(activeEtId)){
      // 保存单个文件
      // 保存单个文件
      let saveEtToServerResTemp = await saveEtToServer(l_doc);
      saveEtToServerRes[activeEtId] = saveEtToServerResTemp ;
    }
  }
  saveEtToServerRes[constEtEnum.CallEtTraceId] = callEtTraceId ;
  saveEtToServerRes[fileInfoEnum.routeId]= param[fileInfoEnum.routeId];
  saveEtToServerRes[fileInfoEnum.officeId] = param[fileInfoEnum.officeId];

  sendWebNotify("SaveET",saveEtToServerRes)
  for(let i=1;i<=count;i++) {
    let l_doc = wps.EtApplication().Workbooks.Item(i)
    // 判断是否是需要保存的文件
    let activeEtId = GetDocParamsValue(l_doc,constEtEnum.ActiveEtId);
    if(paramActiveEtId.includes(activeEtId)){
      l_doc.Close(-1)
    }
  }
  return saveEtToServerRes;
}

/**
 * 关闭WPS活动文档并退出WPS进程
 */
async function SavePDF() {

  let l_doc = wps.EtApplication().ActiveWorkbook
  let savePdfToServerRes = await savePdfoServer(l_doc);
  alert(JSON.stringify(savePdfToServerRes))
  return savePdfToServerRes;

}

/**
 * 打印ET
 */
function PrintTemplateEt(docParams) {

  OpenFile(docParams,(doc)=>{

    let count = doc.Worksheets.Count;
    for(let i=1;i<=count;i++) {
      let sheet = doc.Worksheets.Item(i)
      for (let i = 1; i <= sheet.Comments.Count; i++) {
        let c = sheet.Comments.Item(i)
        let key = c.Text()
        if( !!key && docParams.dateInfo[key]){
          sheet.Comments.Item(i).Parent.Formula = docParams.dateInfo[key]
        }
      }
    }

    setDocParamsValue(doc,constEtEnum.isPrint,true);
    // 打印文件
    doc.PrintOut();
    // 关闭文件
    doc.Close(false);
  });

}


//这些函数是给wps客户端调用的
export default {
  dispatcher
}
